/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
namespace GearBlog.Web.Controllers
{
	using System;
	using System.Net;
	using Castle.MonoRail.ActiveRecordSupport;
	using Castle.MonoRail.Framework;
	using CookComputing.XmlRpc;
	using GearBlog.Web.Filters;
	using GearBlog.Web.Models;
	using GearBlog.Web.Utils;
	using GearBlog.Web.XmlRpc;

	/// <summary>
    /// Summary description for BlogPostController
    /// </summary>
    [Layout("default")]
	[AuthenticationFilter(typeof(FormsAuthenticationAgent), "Admins", "Posters",RequiresLogin = true)]
    public class BlogPostController : ExtendedControllerBase
    {
        public BlogPostController()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public void SavePost([ARDataBind("PostForm", Validate = true, AutoLoad=AutoLoadBehavior.NewInstanceIfInvalidKey)] Post post)
        {
            if (HasValidationError(post))
            {
                PropertyBag["ErrorSummary"] = GetErrorSummary(post);
                RedirectToReferrer();
            }
            else
            {
				//update with edit date if record already exist
                post.CreatedAt = DateTime.Now;
            	post.Author = CurrentUser;
				if (CurrentUser.AutoSubscribeComments)
					post.CommentSubscribers.Add(CurrentUser);

				post.Save();

				//generate notification for all users who wants to subscribe to new post
				Notifier notifier = new Notifier(this);

				if (Models.Setting.Get().SubmitTrackBack)
					TrackBackUtil.Post(post, Context);

				notifier.Notify(post);
                Flash["message"] = "Post saved successfully.";
				BlogPing();
                Redirect("Blog", "index");
            }
        }

        public void ShowAddPost()
        {
			// use new object instead of type to initialize id
        	PropertyBag["PostForm"] = new Post();
        }
		public void ShowEditPost(int id)
		{
			Post post=Post.Find(id);
			if (CurrentUser.IsInRole("Admins")||post.Author.Equals(CurrentUser))
				PropertyBag["PostForm"] = post;
			else
			{
				Flash["Message"] = "Unable to modify post. You have to be an administrator or the post author.";
				RedirectToReferrer();
			}
		}
		/// <summary>
		/// Delete post by Id, administrator can delete all post, while poster can only delete post they originate
		/// </summary>
		public void DeletePost(int id)
		{
			Post post = Post.Find(id);
			User user = SecurityUtil.GetCurrentUser(Context);
			if (user.IsInRole("Admins") || (string.Compare(user.Name, post.Author.UserName, true) == 0))
			{
				post.Delete();
				Flash["message"] = "Post deleted successfully.";
			}
			else
			{
				Flash["message"] = "Unable to delete post. You have to be administrator or post author to delete the post.";
			}
			RedirectToReferrer();
		}

		private void BlogPing()
		{
			if (Setting.PingWebLogs)
			{
				IWebLogsPing webLogsPing = XmlRpcProxyGen.Create<IWebLogsPing>();
				
				try
				{
					if (!string.IsNullOrEmpty(Setting.ProxyHost))
						webLogsPing.Proxy = new WebProxy(string.Format("{0}:{1}", Setting.ProxyHost, Setting.ProxyPort), true);
					webLogsPing.Ping(Setting.Title, GetSiteRootUrl());
				}
				catch (Exception e)
				{
					//blog ping we just need to write log
					Logger.Error("Unable to execute blog ping", e);
				}
			}
		}

		private string GetSiteRootUrl()
		{
			return Context.Request.Uri.GetLeftPart(UriPartial.Authority);
		}
    }
}
